/**
 * 
 */
package org.mspring.mlog.web.module.web.ucenter.admin;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mspring.mlog.entity.Post;
import org.mspring.mlog.entity.PostCatalog;
import org.mspring.mlog.entity.security.User;
import org.mspring.mlog.service.PostCatalogService;
import org.mspring.mlog.service.PostService;
import org.mspring.mlog.service.security.UserService;
import org.mspring.mlog.web.query.PostQueryCriterion;
import org.mspring.mlog.web.security.SecurityUtils;
import org.mspring.platform.dao.support.Page;
import org.mspring.platform.dao.support.Sort;
import org.mspring.platform.utils.StringUtils;
import org.mspring.platform.web.ResponseEntity;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Gao Youbo
 * @since 2013-6-8
 * @description
 * @TODO
 */
@Widget
@RequestMapping("/u/{username}/admin/post")
@SuppressWarnings({ "unchecked", "rawtypes" })
public class UCenterAdmin_PostWidget extends Abstract_UCenterAdminWidget {
    @Autowired
    private PostService postService;
    @Autowired
    private UserService userService;
    @Autowired
    private PostCatalogService postCatalogService;

    @RequestMapping("/list")
    public String list(@ModelAttribute Page<Post> postPage, @ModelAttribute Post post, @RequestParam Map queryParams, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (postPage == null) {
            postPage = new Page<Post>();
        }
        postPage.setPageSize(8);
        postPage.setSort(new Sort("isTop desc, id desc", ""));
        // 默认查看已发布的文章
        if (post == null) {
            post = new Post();
        }
        post.setStatus(Post.Status.PUBLISH);
        queryParams.put("status", Post.Status.PUBLISH);
        queryParams.put("author.id", spaceUser.getId());
        postPage = postService.listPage(new PostQueryCriterion(queryParams), postPage);
        Collections.sort(postPage.getResult(), new Comparator<Post>() {
            @Override
            public int compare(Post o1, Post o2) {
                // TODO Auto-generated method stub
                if (o1.getIsTop() && !o2.getIsTop()) {
                    return -1;
                } else if (!o1.getIsTop() && o2.getIsTop()) {
                    return 1;
                }
                return 0;
            }
        });
        model.addAttribute("postPage", postPage);
        return "skin:/ucenter/admin/post/list";
    }

    @RequestMapping("/create")
    public String create(@ModelAttribute Post post, HttpServletRequest request, HttpServletResponse response, Model model) {
        // 文章分类
        List<PostCatalog> catalogs = postCatalogService.findPostCatalogByUser(spaceUser.getId());
        model.addAttribute("catalogs", catalogs);

        // 是否开启评论
        model.addAttribute("commentStatus", Post.CommentStatus.getCommentStatusMap());

        Map<String, String> isTop = new HashMap<String, String>();
        isTop.put("true", "置顶");
        isTop.put("false", "不置顶");
        model.addAttribute("isTop", isTop);
        return "skin:/ucenter/admin/post/create";
    }

    @RequestMapping("/create/do")
    public String create_do(@ModelAttribute Post post, HttpServletRequest request, HttpServletResponse response, Model model) {
        try {
            if (post.getAuthor() == null) {
                post.setAuthor(SecurityUtils.getCurrentUser(request));
            }
            post.setPostIp(request.getRemoteAddr());
            postService.save(post);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return String.format("redirect:/u/%s/admin/post/list", spaceUser.getName());
    }

    @RequestMapping("/edit")
    public String edit(@RequestParam(required = false) Long id, @ModelAttribute Post post, HttpServletRequest request, HttpServletResponse response, Model model) {
        post = postService.get(id);
        if (post == null) {
            return prompt(model, "未找到要修改的文章");
        }
        if (post.getAuthor().getId() != spaceUser.getId()) {
            return prompt(model, "无权修改此文章");
        }
        model.addAttribute("post", post);

        // 文章分类
        List<PostCatalog> catalogs = postCatalogService.findPostCatalogByUser(spaceUser.getId());
        model.addAttribute("catalogs", catalogs);

        // 是否开启评论
        model.addAttribute("commentStatus", Post.CommentStatus.getCommentStatusMap());

        Map<String, String> isTop = new HashMap<String, String>();
        isTop.put("true", "置顶");
        isTop.put("false", "不置顶");
        model.addAttribute("isTop", isTop);

        return "skin:/ucenter/admin/post/edit";
    }

    @RequestMapping("/edit/do")
    public String edit_do(@RequestParam(required = false) Long id, @ModelAttribute Post post, HttpServletRequest request, HttpServletResponse response, Model model) {
        postService.updatePost(post);
        return String.format("redirect:/u/%s/admin/post/list", spaceUser.getName());
    }

    @RequestMapping("/delete")
    @ResponseBody
    public ResponseEntity delete(@RequestParam Long id, @ModelAttribute Page<Post> postPage, @ModelAttribute Post post, @RequestParam Map queryParams, HttpServletResponse request, HttpServletResponse response) {
        ResponseEntity rsp = new ResponseEntity();
        try {
            postService.safeRemove(id, spaceUser.getId());
            rsp.setSuccess(true);
            return rsp;
        } catch (Exception e) {
            rsp.setSuccess(false);
            rsp.setMessage(e.getMessage());
            return rsp;
        }
    }

    @RequestMapping("/autosave")
    @ResponseBody
    public String autosave(@ModelAttribute Post post, HttpServletRequest request, HttpServletResponse response, Model model) {
        User user = SecurityUtils.getCurrentUser(request);
        if (post.getAuthor() == null) {
            post.setAuthor(user);
        }
        if (StringUtils.isBlank(post.getTitle())) {
            post.setTitle("无标题");
        }
        if (post.getCatalog() == null || post.getCatalog().getId() == null) {
            post.setCatalog(null);
        }
        post.setPostIp(request.getRemoteAddr());
        post.setStatus(Post.Status.DRAFT);
        post = postService.merge(post);
        return post.getId().toString();
    }

    /**
     * 草稿箱
     * 
     * @param postPage
     * @param post
     * @param queryParams
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/draft")
    public String draft(@ModelAttribute Page<Post> postPage, @ModelAttribute Post post, @RequestParam Map queryParams, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (postPage == null) {
            postPage = new Page<Post>();
        }
        postPage.setPageSize(8);
        postPage.setSort(new Sort("id", Sort.DESC));
        // 默认查看已发布的文章
        if (post == null) {
            post = new Post();
        }
        post.setStatus(Post.Status.DRAFT);
        queryParams.put("status", Post.Status.DRAFT);
        queryParams.put("author.id", spaceUser.getId());
        postPage = postService.listPage(new PostQueryCriterion(queryParams), postPage);
        Collections.sort(postPage.getResult(), new Comparator<Post>() {
            @Override
            public int compare(Post o1, Post o2) {
                // TODO Auto-generated method stub
                if (o1.getIsTop() && !o2.getIsTop()) {
                    return -1;
                } else if (!o1.getIsTop() && o2.getIsTop()) {
                    return 1;
                }
                return 0;
            }
        });
        model.addAttribute("postPage", postPage);
        return "skin:/ucenter/admin/post/draft";
    }
}
